/**
 * 
 */
package com.effectiv.gooruda.rest.argumentresolver;

import jodd.util.StringUtil;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.impl.FacebookTemplate;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;

import com.effectiv.gooruda.domain.SocialProvider;
import com.effectiv.gooruda.repository.SocialProviderRepository;

/**
 * @author Dhrubo
 * 
 */
@Slf4j
public class FacebookArgumentResolver implements WebArgumentResolver{
	
	@Getter @Setter
	private SocialProviderRepository repository;
	
	@Override
	public Object resolveArgument(MethodParameter param,
			NativeWebRequest request) throws Exception {
		Object argument = UNRESOLVED;

		log.info("Resolving custom argument");
		
		if (param.getParameterType().equals(Facebook.class)) {
			Facebook facebook = null;
			
			String providerKey = request.getHeader("provider-key");
			
			SocialProvider provider = repository.findByProviderKey(providerKey);
			
			if(StringUtil.isEmpty(provider.getProviderKey())) {
				 facebook = new FacebookTemplate(provider.getKey1());
			}
			else{
				 facebook = new FacebookTemplate(provider.getKey1(), provider.getKey2());
			}
				
			argument = facebook;
		}

		
		
		return argument;
	}

	

}
